/**
 * 数据增强工具
 * 用于根据ID查找并渲染客户、公司、员工等信息
 */

import { customerApi } from '@/api/customerApi';
import { companyApi } from '@/api/companyApi';
import employeeApi from '@/api/employeeApi';

// 缓存对象，避免重复请求
const cache = {
  customers: new Map(),
  companies: new Map(),
  employees: new Map()
};

/**
 * 获取客户信息
 * @param {number} customerId - 客户ID
 * @returns {Promise<string>} - 客户名称
 */
export const getCustomerName = async (customerId) => {
  if (!customerId) return '未分配';
  
  // 检查缓存
  if (cache.customers.has(customerId)) {
    return cache.customers.get(customerId);
  }
  
  try {
    const response = await customerApi.getCustomerDetail(customerId);
    if (response.code === 200 && response.data) {
      const customerName = response.data.name || '未知客户';
      cache.customers.set(customerId, customerName);
      return customerName;
    }
  } catch (error) {
    console.error('获取客户信息失败:', error);
  }
  
  return '未知客户';
};

/**
 * 获取公司信息
 * @param {number} companyId - 公司ID
 * @returns {Promise<string>} - 公司名称
 */
export const getCompanyName = async (companyId) => {
  if (!companyId) return '未分配';
  
  // 检查缓存
  if (cache.companies.has(companyId)) {
    return cache.companies.get(companyId);
  }
  
  try {
    const response = await companyApi.getCompanyDetail(companyId);
    if (response.code === 200 && response.data) {
      const companyName = response.data.name || '未知公司';
      cache.companies.set(companyId, companyName);
      return companyName;
    }
  } catch (error) {
    console.error('获取公司信息失败:', error);
  }
  
  return '未知公司';
};

/**
 * 获取员工信息
 * @param {number} employeeId - 员工ID
 * @returns {Promise<string>} - 员工姓名
 */
export const getEmployeeName = async (employeeId) => {
  if (!employeeId) return '未分配';
  
  // 检查缓存
  if (cache.employees.has(employeeId)) {
    return cache.employees.get(employeeId);
  }
  
  try {
    const response = await employeeApi.getEmployeeDetail(employeeId);
    if (response.code === 200 && response.data) {
      const employeeName = response.data.name || '未知员工';
      cache.employees.set(employeeId, employeeName);
      return employeeName;
    }
  } catch (error) {
    console.error('获取员工信息失败:', error);
  }
  
  return '未知员工';
};

/**
 * 批量获取客户信息
 * @param {Array<number>} customerIds - 客户ID数组
 * @returns {Promise<Map>} - 客户ID到名称的映射
 */
export const getCustomerNames = async (customerIds) => {
  const result = new Map();
  const uncachedIds = [];
  
  // 先检查缓存
  customerIds.forEach(id => {
    if (id && cache.customers.has(id)) {
      result.set(id, cache.customers.get(id));
    } else if (id) {
      uncachedIds.push(id);
    }
  });
  
  // 批量获取未缓存的客户信息
  if (uncachedIds.length > 0) {
    try {
      const promises = uncachedIds.map(id => customerApi.getCustomerDetail(id));
      const responses = await Promise.allSettled(promises);
      
      responses.forEach((response, index) => {
        const id = uncachedIds[index];
        if (response.status === 'fulfilled' && response.value.code === 200) {
          const customerName = response.value.data?.name || '未知客户';
          result.set(id, customerName);
          cache.customers.set(id, customerName);
        } else {
          result.set(id, '未知客户');
        }
      });
    } catch (error) {
      console.error('批量获取客户信息失败:', error);
      uncachedIds.forEach(id => {
        result.set(id, '未知客户');
      });
    }
  }
  
  return result;
};

/**
 * 批量获取公司信息
 * @param {Array<number>} companyIds - 公司ID数组
 * @returns {Promise<Map>} - 公司ID到名称的映射
 */
export const getCompanyNames = async (companyIds) => {
  const result = new Map();
  const uncachedIds = [];
  
  // 先检查缓存
  companyIds.forEach(id => {
    if (id && cache.companies.has(id)) {
      result.set(id, cache.companies.get(id));
    } else if (id) {
      uncachedIds.push(id);
    }
  });
  
  // 批量获取未缓存的公司信息
  if (uncachedIds.length > 0) {
    try {
      const promises = uncachedIds.map(id => companyApi.getCompanyDetail(id));
      const responses = await Promise.allSettled(promises);
      
      responses.forEach((response, index) => {
        const id = uncachedIds[index];
        if (response.status === 'fulfilled' && response.value.code === 200) {
          const companyName = response.value.data?.name || '未知公司';
          result.set(id, companyName);
          cache.companies.set(id, companyName);
        } else {
          result.set(id, '未知公司');
        }
      });
    } catch (error) {
      console.error('批量获取公司信息失败:', error);
      uncachedIds.forEach(id => {
        result.set(id, '未知公司');
      });
    }
  }
  
  return result;
};

/**
 * 批量获取员工信息
 * @param {Array<number>} employeeIds - 员工ID数组
 * @returns {Promise<Map>} - 员工ID到名称的映射
 */
export const getEmployeeNames = async (employeeIds) => {
  const result = new Map();
  const uncachedIds = [];
  
  // 先检查缓存
  employeeIds.forEach(id => {
    if (id && cache.employees.has(id)) {
      result.set(id, cache.employees.get(id));
    } else if (id) {
      uncachedIds.push(id);
    }
  });
  
  // 批量获取未缓存的员工信息
  if (uncachedIds.length > 0) {
    try {
      const promises = uncachedIds.map(id => employeeApi.getEmployeeDetail(id));
      const responses = await Promise.allSettled(promises);
      
      responses.forEach((response, index) => {
        const id = uncachedIds[index];
        if (response.status === 'fulfilled' && response.value.code === 200) {
          const employeeName = response.value.data?.name || '未知员工';
          result.set(id, employeeName);
          cache.employees.set(id, employeeName);
        } else {
          result.set(id, '未知员工');
        }
      });
    } catch (error) {
      console.error('批量获取员工信息失败:', error);
      uncachedIds.forEach(id => {
        result.set(id, '未知员工');
      });
    }
  }
  
  return result;
};

/**
 * 增强项目数据，添加关联信息
 * @param {Array} projects - 项目数据数组
 * @returns {Promise<Array>} - 增强后的项目数据数组
 */
export const enhanceProjectData = async (projects) => {
  if (!Array.isArray(projects) || projects.length === 0) {
    return projects;
  }
  
  // 收集所有需要查询的ID
  const customerIds = [...new Set(projects.map(p => p.customer_id).filter(Boolean))];
  const companyIds = [...new Set(projects.map(p => p.contract_company_id).filter(Boolean))];
  const employeeIds = [...new Set([
    ...projects.map(p => p.manager_id).filter(Boolean),
    ...projects.map(p => p.director_id).filter(Boolean)
  ])];
  
  // 并行获取所有关联数据
  const [customerNames, companyNames, employeeNames] = await Promise.all([
    getCustomerNames(customerIds),
    getCompanyNames(companyIds),
    getEmployeeNames(employeeIds)
  ]);
  
  // 增强项目数据
  return projects.map(project => ({
    ...project,
    customerName: customerNames.get(project.customer_id) || '未分配',
    contractCompanyName: companyNames.get(project.contract_company_id) || '未分配',
    managerName: employeeNames.get(project.manager_id) || '未分配',
    directorName: employeeNames.get(project.director_id) || '未分配'
  }));
};

/**
 * 增强单个项目数据
 * @param {Object} project - 项目数据
 * @returns {Promise<Object>} - 增强后的项目数据
 */
export const enhanceSingleProjectData = async (project) => {
  if (!project) return project;
  
  const [customerName, companyName, managerName, directorName] = await Promise.all([
    getCustomerName(project.customer_id),
    getCompanyName(project.contract_company_id),
    getEmployeeName(project.manager_id),
    getEmployeeName(project.director_id)
  ]);
  
  return {
    ...project,
    customerName,
    contractCompanyName: companyName,
    managerName,
    directorName
  };
};

/**
 * 清除缓存
 */
export const clearCache = () => {
  cache.customers.clear();
  cache.companies.clear();
  cache.employees.clear();
};

/**
 * 清除特定类型的缓存
 * @param {string} type - 缓存类型 ('customers', 'companies', 'employees')
 */
export const clearCacheByType = (type) => {
  if (cache[type]) {
    cache[type].clear();
  }
};
